import { Module } from 'vuex'
import type { TRootState } from '../type'
import type { TLoginState } from './type'

import { phoneLogin, getUserPlayList } from '@/service/login'
import localCache from '@/utils/cache'

const loginModule: Module<TLoginState, TRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      account: null,
      profile: null,
      cookie: '',
      userPlayList: [] // 用户创建和收藏的歌单列表
    }
  },
  getters: {
    getUserSonglist(state) {
      return state.userPlayList
    }
  },
  mutations: {
    saveToken(state, token: string) {
      state.token = token
    },
    saveCookie(state, cookie: string) {
      state.cookie = cookie
    },
    saveProfile(state, profile: any) {
      state.profile = profile
    },
    saveAccount(state, account: any) {
      state.account = account
    },
    updateUserSongList(state, list: any) {
      state.userPlayList = list
    }
  },
  actions: {
    async phoneLoginAction({ commit }, pyload) {
      // console.log('执行账号登录逻辑' + pyload)
      //登录并获取保存token cookie
      const result = await phoneLogin(pyload)
      const { token, profile, account, cookie } = result
      const listRes: any = await getUserPlayList(profile.userId)
      commit('updateUserSongList', listRes.playlist)
      localCache.setCache('playlist', listRes.playlist)
      commit('saveToken', token)
      localCache.setCache('token', token)
      commit('saveCookie', cookie)
      localCache.setCache('cookie', cookie)
      commit('saveProfile', profile)
      localCache.setCache('profile', profile)
      commit('saveAccount', account)
    },
    loginOut({ commit }) {
      // 退出登录
      commit('saveToken', '')
      commit('saveProfile', null)
      commit('saveAccount', null)
      commit('saveCookie', '')
      commit('updateUserSongList', [])
      localCache.deleteCache('token')
      localCache.deleteCache('profile')
      localCache.deleteCache('cookie')
      localCache.deleteCache('playlist')
    },
    loadLocalLogin({ commit }) {
      //初始化本地数据与vuex数据联系
      const token = localCache.getCache('token')
      const cookie = localCache.getCache('cookie')
      const profile = localCache.getCache('profile')
      const playlist = localCache.getCache('playlist')
      if (token) {
        commit('saveToken', token)
      }
      if (cookie) {
        commit('saveCookie', cookie)
      }
      if (profile) {
        commit('saveProfile', profile)
      }
      if (playlist) {
        commit('updateUserSongList', playlist)
      }
    }
  }
}
export default loginModule
